package com.tian.asyn;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tian.config.RedisConfig;
import com.tian.entity.SystemMessageTemplate;
import com.tian.entity.SystemUserMessage;
import com.tian.entity.User;
import com.tian.enums.SystemUserMessageStatusEnum;
import com.tian.mapper.SystemMessageTemplateMapper;
import com.tian.mapper.SystemUserMessageMapper;
import com.tian.mapper.UserMapper;
import com.tian.mongo.domain.UserMessage;
import com.tian.mongo.service.UserMessageService;
import com.tian.util.RedisConstantPre;
import com.tian.util.SnowflakeIdWorker;
import com.tian.util.StringUtil;
import com.tian.util.TwoDimensionalCodeGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * 2023年11月22日 10:14
 * 在线刷题 1200+题和1000+篇干货文章：<a href="https://woaijava.cc/">博客地址</a>
 * <p>
 * 异步发送站内信
 */
@Slf4j
@Component
public class SystemUserMessageAsynchronous {
    @Resource
    private SystemUserMessageMapper systemUserMessageMapper;

    @Resource
    private SystemMessageTemplateMapper systemMessageTemplateMapper;

    @Resource
    private RedisConfig redisConfig;
    @Resource
    private UserMessageService userMessageService;

    /**
     * 无参数的站内信
     *
     * @param userId    用户id
     * @param messageId 模板id
     */
    @Async("asyncThreadPool")
    public void sendSystemUserMessageNoParams(Integer userId, Integer messageId) {
        SystemMessageTemplate systemMessageTemplate = this.getSystemMessageTemplate(userId, messageId);
        if (systemMessageTemplate == null) {
            log.error("【mysql】站内信发送失败，userId={}，其中 messageId={}不存在", userId, messageId);
            return;
        }
        SystemUserMessage systemUserMessage = new SystemUserMessage();
        systemUserMessage.setStatus(SystemUserMessageStatusEnum.UN_READ.getStatus());
        systemUserMessage.setMessage(systemMessageTemplate.getContent());
        systemUserMessage.setReceiverId(userId);
        systemUserMessage.setCreateTime(new Date());
        systemUserMessageMapper.insert(systemUserMessage);
    }

    /**
     * 采用mongoDB存储站内信
     *
     * @param userId    用户id
     * @param messageId 站内信模板id
     */
    @Async("asyncThreadPool")
    public void sendSystemUserMessageNoParamsMongoDb(Integer userId, Integer messageId, Map<String, String> paramMap) {
        SystemMessageTemplate systemMessageTemplate = this.getSystemMessageTemplate(userId, messageId);
        if (systemMessageTemplate == null) {
            log.error("【MongoDB】站内信发送失败，userId={}，其中 messageId={}不存在", userId, messageId);
            return;
        }
        String content = systemMessageTemplate.getContent();
        //是否有参数需要动态替换
        if (CollectionUtil.isNotEmpty(paramMap)) {
            String params = systemMessageTemplate.getParams();
            if (StringUtil.isBlank(params)) {
                log.error("【MongoDB】站内信发送失败，userId={}，其中 messageId={}中的参数没有配置", userId, messageId);
                return;
            }
            String[] split = params.split("\\|");
            for (String s : split) {
                content = content.replace(s, paramMap.get(s));
            }
        }

        UserMessage userMessage = new UserMessage();
        userMessage.setStatus(SystemUserMessageStatusEnum.UN_READ.getStatus());
        userMessage.setMessage(content);
        userMessage.setReceiverId(userId);
        userMessage.setCreateTime(new Date());
        userMessageService.saveUser(userMessage);
    }

    private SystemMessageTemplate getSystemMessageTemplate(Integer userId, Integer messageId) {
        String key = RedisConstantPre.SYSTEM_MESSAGE_PRE + messageId;
        String s = redisConfig.get(key);
        SystemMessageTemplate systemMessageTemplate;
        if (StringUtil.isBlank(s)) {
            systemMessageTemplate = systemMessageTemplateMapper.selectByPrimaryKey(messageId);
            if (systemMessageTemplate != null) {
                redisConfig.set(key, JSON.toJSONString(systemMessageTemplate));
            }
        } else {
            systemMessageTemplate = JSON.parseObject(redisConfig.get(key), SystemMessageTemplate.class);
        }
        return systemMessageTemplate;
    }
}
